package org.maitaole.interceptor;

import org.maitaole.commons.Constant;
import org.maitaole.entity.SysUser;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *  Authentication: 认证。
 *  Authorization: 授权。
 * 用户认证的拦截器:
 */
public class AuthorizationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        /**
         * 从session获取用户登录成功之后存放的用户信息
         */
        SysUser sysUser = (SysUser)session.getAttribute(Constant.USER_INFO_ATTR);

        // 如果值为空，表示 LoginController 肯定没有执行  session.setAttribute(Constant.USER_INFO_ATTR, sysUser);
        if(null == sysUser) {
            /**
             * 设置状态状态码：401
             *               403
             */
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        return true;
    }
}
